import HttpUtils from "../../common/utils/HttpUtils";
import EventEmitterUtils from "../../common/utils/EventEmitterUtils";
import StorageUtils from "../../common/utils/StorageUtils";
import ToastUtils from "@page/common/utils/ToastUtils";
import InfoModal from "@page/common/modal/InfoModal";
import CarouselModal from "@page/common/modal/CarouselModal";
import urlHook from "@page/common/utils/urlHook";
import REST from "@module/Rest";
import EventApi from "@module/EventApi";
import ZenModal from "@module/../components/ZenUI/ZenModal/ZenModal";

export default class TwoBtns extends React.Component {
    constructor() {
        super();
        this.state = {
            run: false,
            isInteresting: false,
            modalMsg: "",
            showGroupBtn: false,
            // showGroupBtn:true,
            groupbuyingId: null,
            PmAddCarBtn: true //购物车权限状态
        };
    }

    componentDidMount() {
        this.isInterestProduct();
        this.addEvent();
        this.pmAddCarBtn();
    }

    addEvent() {
        EventApi.on("showGroupBuyingBtn", res => {
            let groupbuyingId = res.groupbuyingId;
            let groupBuyingInfo = res.groupBuyingInfo;
            this.setState({
                showGroupBtn: true,
                groupbuyingId: groupbuyingId,
                groupBuyingInfo: groupBuyingInfo
            });
        });
    }

    // 是否关注商品
    isInterestProduct() {
        const { productId } = this.props;

        let url = `/store/api/user/buyer/isInterestProduct`;
        REST.post(url, { productSn: productId }).then(
            data => {
                this.setState({ isInteresting: data.isInteresting });
            },
            error => {}
        );
    }

    //关注商品
    interestProduct() {
        let url = `/store/api/user/buyer/updateInterestProduct`;
        const { productId } = this.props;
        let params = {
            productSns: [productId],
            isInteresting: !this.state.isInteresting
        };
        REST.post(url, params).then(
            data => {
                this.setState({ isInteresting: params.isInteresting });
            },
            error => {}
        );
    }

    //购物车按钮权限
    pmAddCarBtn() {
        let pmList = Uts.storage.get("STORE_USERPERMISSION") || [];
        if (pmList.indexOf("商品下单") == -1) {
            if (global.hasLogin) {
                this.setState({ PmAddCarBtn: false });
            }
        }
        if (global.isSupp) {
            this.setState({ PmAddCarBtn: false });
        }
    }

    addCart() {
        if (!this.state.PmAddCarBtn) {
            return;
        }
        if (!this.isProductEnough()) {
            this.setState({ modalMsg: "商品库存不够" });
            this.infoModal.showModal();
            return;
        }

        this.saveToShopCart();
    }

    isProductEnough() {
        const { product, productCount } = this.props;
        const { sku } = product;

        if (sku - productCount < 0) {
            return false;
        }
        return true;
    }

    saveToShopCart() {
        const { productId, productCount } = this.props;

        if (!global.hasLogin) {
            StorageUtils.saveCartCountToLocal(productCount);
            StorageUtils.saveCartInfoToLocal(productId, productCount);
            EventEmitterUtils.emit("updateShopCartNum", null);
            this.animateRun();
            return;
        }

        if (Uts.getCookie("orgId") == 3 || Uts.getCookie("orgId") == 37) {
            let devideCategory = [700, 60, 61, 62, 63];
            let jidaCategory = [701, 66, 1563, 1571, 1578, 1584, 1593, 1610];//仅对暨大限制办公类1000元以上的商品下单
            let isMatch = false;
            Uts.each(this.props.product.category, function(item, index) {
                if(Uts.getCookie("orgId") == 37){
                    if (Uts.contain(jidaCategory, item.id)) {
                        isMatch = true;
                    }
                }
                if (Uts.contain(devideCategory, item.id)) {
                    isMatch = true;
                }
            });
            if (isMatch && this.props.product.price >= 1000) {
                function closeModal(value) {
                    // console.log("run closeModal", value);
                    modal.remove();
                }

                function Content(props) {
                    return (
                        <div className="zen_fs-14">
                            <div className="zen_t-c zen_m-b-20 zen_m-t-30">
                                {Uts.getCookie("orgId") == 37?"采购仪器设备或办公用品单价不能超过1000元":"采购仪器设备单价不能超过1000元"}
                            </div>
                            <div className="zen_ps-ab zen_b-40 zen_l-140">
                                <span
                                    className="zen_cur-p zen_p-h-40 zen_p-v-10 zen_bg-0093EB zen_bdr-4 zen_white "
                                    onClick={closeModal}
                                >
                                    知道了
                                </span>
                            </div>
                        </div>
                    );
                }
                let options = {
                    header: "提示",
                    modalClass: "zen_bdr-5 detail-zen-model",
                    // footer: "test footer",
                    content: Content,
                    size: "sm",
                    hideFooter: true,
                    // cbList: [closeModal],
                    close: closeModal
                };
                let modal = ZenModal.loadModal(options);
                modal.show();

                return false;
            }
        }

        HttpUtils.saveToShoppingCart(productCount, productId)
            .then(res => {
                console.log(res);
                if (res.code == "0000") {
                    this.animateRun();

                    EventEmitterUtils.emit("updateShopCartNum", null);
                } else if (res.code == "0002") {
                    this.setState({ modalMsg: res.message });
                    setTimeout(() => {
                        this.infoModal.showModal();
                    }, 100);
                    return;
                } else if (res.code == "0009") {
                    this.showModal(res.message);
                    return;
                } else if (res.code == "4001") {
                    this.setState({ modalMsg: res.errModels[0].errMsg });
                    setTimeout(() => {
                        this.infoModal.showModal();
                    }, 100);
                    return;
                } else {
                    this.setState({
                        modalMsg: res.message
                    });
                    setTimeout(() => {
                        this.infoModal.showModal();
                    }, 100);
                }
            })
            .catch(err => {
                console.log(err);
            });
    }

    //开启动画
    animateRun() {
        this.setState({
            run: true
        });
        setTimeout(() => {
            this.setState({
                run: false
            });
        }, 2000);
    }

    //判断是否有团购权限
    getGroupCartInfo() {
        let url = `/store/api/group-buying/application/shopping-list`;
        const { productId, productCount } = this.props;
        const { groupbuyingId } = this.state;
        const idArr = productId.split(",");
        let params = {
            productIds: idArr,
            productQuantity: productCount,
            groupBuyingId: groupbuyingId
            // groupBuyingId:"d1e461dc-dcdf-41cc-b56e-d0b21ef0960f"
        };
        REST.post(url, params, "show0002")
            .then(res => {
                console.log(res);
                if (res.code == "0000") {
                    $state.go({
                        stateName: "/statements",
                        params: {
                            productCount,
                            ids: productId,
                            // ids:"200000229443",
                            groupbuyingId: groupbuyingId
                            // groupbuyingId:'2dc3b3e1-8b16-4fae-a434-25e7ce152dd7',
                        }
                    });
                } else if (res.code == "0009") {
                    this.showModal(res.message);
                }
            })
            .catch(err => {});
    }

    showModal = message => {
        function closeModal(value) {
            console.log("run closeModal", value);
            modal.hide();
        }

        function Content(props) {
            props.item.passParams && props.item.passParams("abc");
            return (
                <div className="zen_fs-14">
                    <div className="zen_t-c zen_m-b-20">
                        以下商品已下架或贵单位禁止采购，请重新选择商品
                    </div>
                    <div
                        className="zen_t-c zen_969696"
                        dangerouslySetInnerHTML={{ __html: message }}
                    />
                    <div className="zen_ps-ab zen_b-40 zen_l-140">
                        <span
                            className="zen_cur-p zen_p-h-40 zen_p-v-10 zen_bg-0093EB zen_bdr-4 zen_white "
                            onClick={closeModal}
                        >
                            知道了
                        </span>
                    </div>
                </div>
            );
        }
        let options = {
            header: "提示",
            modalClass: "zen_bdr-5 detail-zen-model",
            // footer: "test footer",
            content: Content,
            size: "sm",
            hideFooter: true,
            // cbList: [closeModal],
            close: closeModal
        };
        let modal = ZenModal.loadModal(options);
        modal.show();
    };

    //立即下单
    goToBuy(e) {
        e.stopPropagation();
        if (!this.isProductEnough()) {
            this.setState({ modalMsg: "商品库存不够" });
            this.infoModal.showModal();
            return;
        }

        let url = `/store/api/order/getDeptsW`;
        const { productId, productCount } = this.props;

        const { groupbuyingId } = this.state;
        REST.post(url, {}, "dis").then(
            res => {
                console.log(res);
                if (res.code == "0000") {
                    // window.location.href=urlHook.groupBuyingOrder(productCount,productId,groupbuyingId)

                    //判断是否有权限
                    this.getGroupCartInfo();
                } else {
                    this.setState({
                        modalMsg: res.message
                    });
                    setTimeout(() => {
                        this.infoModal.showModal();
                    }, 100);
                }
            },
            error => {}
        );
    }

    render() {
        const {
            run,
            modalMsg,
            isInteresting,
            showGroupBtn,
            PmAddCarBtn
        } = this.state;
        const { productCount, product } = this.props;

        return (
            <div className={"detail-top-two-btns"}>
                {this.renderRightBtn()}
                {global.hasLogin && (
                    <div
                        onClick={() => this.interestProduct()}
                        className={"detail-top-btns-yes"}
                    >
                        <p>{isInteresting ? "取消关注" : "加入关注"}</p>
                    </div>
                )}

                {
                    <div className={this.getClassName(run)}>
                        <em
                            className={"detail-top-btns-num-run-em"}
                        >{`+${productCount}`}</em>
                    </div>
                }
                <InfoModal
                    getRef={v => (this.infoModal = v)}
                    content={modalMsg}
                />
                <CarouselModal
                    getRef={v => (this.carouselModal = v)}
                    content={modalMsg}
                />
            </div>
        );
    }

    renderRightBtn() {
        const { showGroupBtn, groupBuyingInfo, PmAddCarBtn } = this.state;
        // const {product}=this.props
        let canNotBuy =
            groupBuyingInfo &&
            groupBuyingInfo.productInGroupBuyingModel &&
            groupBuyingInfo.productInGroupBuyingModel.status == "30";
        let reason =
            groupBuyingInfo &&
            groupBuyingInfo.productInGroupBuyingModel &&
            groupBuyingInfo.productInGroupBuyingModel.reason;
        if (showGroupBtn) {
            if (!canNotBuy) {
                return (
                    <div
                        onClick={e => this.goToBuy(e)}
                        className={"detail-top-btns-no"}
                    >
                        <p>{"立即下单"}</p>
                    </div>
                );
            } else {
                return (
                    <div>
                        <div
                            className={
                                "detail-top-btns-stop detail-top-btn-no-disabled"
                            }
                        >
                            <p style={{ color: "#fff" }}>{"暂停下单"}</p>
                        </div>
                        <div className={"detail-stop-buy-reason"}>
                            {reason ? reason : ""}
                        </div>
                    </div>
                );
            }
        } else {
            return (
                <div
                    onClick={() => this.addCart()}
                    className={Uts.sc([
                        "detail-top-btns-no",
                        global.hasLogin ? "" : "detail-top-btns-no1",
                        !PmAddCarBtn ? "detail-top-btn-no-disabled" : ""
                    ])}
                >
                    <p>加入购物车</p>
                </div>
            );
        }
    }

    getClassName(run) {
        if (!global.hasLogin) {
            if (run) {
                return "detail-top-btns-num-run1-unlogin";
            } else {
                return "detail-top-btns-num-run-unlogin";
            }
        } else {
            if (run) {
                return "detail-top-btns-num-run1";
            } else {
                return "detail-top-btns-num-run";
            }
        }
    }
}
